<!-- 黑名单配置 -->
<template>
	<div>
		<!-- 搜索表单 -->
		<yd-form :options="formOptions" :model="searchFormData" :btns="formBtns" class="mt10"></yd-form>

		<!-- 数据列表 -->
		<YdTable
			:formData="searchFormData"
			:tableConfig="tableConfig"
			:tableData="tableData"
			@sizeChangeHandler="handlerQuery"
			@currentChangeHandler="handlerQuery"
			@sortChangeHandler="handlerQuery"
			@selectionChangeHandler="handlerSelectionChange"
		>
		</YdTable>

		<!-- 添加或修改参数配置对话框 -->
		<el-dialog :title="dialog.addOrUpdate.title" v-model="dialog.addOrUpdate.open" width="600px" append-to-body center>
			<el-form ref="addOrUpdateForm" :model="dialog.addOrUpdate.form" :rules="dialog.addOrUpdate.rule" label-width="120px">
				<el-form-item label="类型" prop="type">
					<el-select v-model="dialog.addOrUpdate.form.type" placeholder="请选择类型" style="width: 100%">
						<el-option v-for="(option, index) in blackTypeOptionsCopy" :key="index" :label="option.label" :value="option.value"> </el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="key" prop="key">
					<el-input v-model="dialog.addOrUpdate.form.key" placeholder="请输入key"></el-input>
				</el-form-item>
				<el-form-item label="value" prop="value">
					<el-input v-model="dialog.addOrUpdate.form.value" placeholder="请输入value"></el-input>
				</el-form-item>
				<el-form-item label="是否启用" prop="isEnable">
					<el-radio-group v-model="dialog.addOrUpdate.form.isEnable">
						<el-radio-button :label="0">否</el-radio-button>
						<el-radio-button :label="1">是</el-radio-button>
					</el-radio-group>
				</el-form-item>
			</el-form>
			<template #footer class="dialog-footer">
				<el-button type="primary" @click="handlerSubmit" :loading="dialog.addOrUpdate.btnLoading">确 定</el-button>
				<el-button @click="closeAddOrUpdateDialog">取 消</el-button>
			</template>
		</el-dialog>
	</div>
</template>

<script setup name="BlackList" lang="tsx">
import { blackWhiteListOptions } from '@/utils/management/commonOptions';
import { list, add, edit, remove } from '@/api/management/resourceManage/blackList';
import useCurrentInstance from '@/utils/useCurrentInstance';
import { ref, reactive, onMounted } from 'vue';

const { proxy } = useCurrentInstance();

const statusOptions = ref<any>([
	{ label: '是', value: 1 },
	{ label: '否', value: 0 },
]);
// 选项
let options = reactive(blackWhiteListOptions());
const formOptions = reactive<FormOptionType>([
	{
		type: 'select',
		label: '类型',
		prop: 'type',
		children: options.blackTypeOptions,
		selectKey: 'value',
		isInitValue: false,
	},
	{
		type: 'select',
		label: '是否启用',
		prop: 'isEnable',
		children: statusOptions,
		selectKey: 'value',
		isInitValue: false,
	},
	{
		type: 'input',
		label: 'key',
		prop: 'key',
		attrs: {
			clearable: true,
		},
	},
	{
		type: 'input',
		label: 'value',
		prop: 'value',
		attrs: {
			clearable: true,
		},
	},
]);
const formBtns = reactive<BtnType[]>([
	{
		type: 'primary',
		text: '查询',
		handler: handlerQuery,
	},
]);
// 搜索表单数据
let searchFormData = reactive<anyObj>({
	orderByColumn: '',
	isAsc: '',
});
// 列表配置
let tableConfig = reactive({
	columns: [
		{
			label: '类型',
			prop: 'type',
			formatter: (row: anyObj, val: any) => {
				// let obj = options.blackTypeOptions[val]
				let obj = options.blackTypeOptions.find((item: any) => item.value === val);
				return obj?.label ?? '';
			},
		},
		{
			label: 'key',
			prop: 'key',
			showOverFlowToolTip: true,
		},
		{
			label: 'value',
			prop: 'value',
			showOverFlowToolTip: true,
		},
		{
			label: '是否启用',
			prop: 'isEnable',
			render: (row: anyObj, val: ApiVal) => {
				// if (proxy.checkRole(['admin']) || proxy.checkPermi(['resource:black:enable'])) {
				return <el-switch value={row.isEnable} active-value={1} inactive-value={0} onChange={(v: number) => statusChange(row, v)}></el-switch>;
				// }
				// return (
				//   <el-switch v-model={row.isEnable} disabled
				//     active-value={1}
				//     inactive-value={0}
				//   >
				//   </el-switch>
				// )
			},
		},
	],
	// 工具栏
	toolBar: [
		{ name: '新增', icon: 'yd-icon-plus', permi: ['resource:black:add'], handler: () => handlerAdd(addFilter) },
		{ name: '修改', icon: 'yd-icon-edit', disable: 'single', permi: ['resource:black:edit'], handler: () => handlerEdit() },
		{ name: '删除', icon: 'yd-icon-delete', disable: 'multiple', permi: ['resource:black:delete'], handler: () => handlerDelete() },
	],
	// 开启复选框
	enableSelection: true,
	// 开启分页
	pagination: {
		pageSize: 10,
		pageNum: 1,
		total: 0,
	},
	// 加载层
	loading: true,
});
// 列表数据
let tableData = ref([]);
// 黑名单类型下拉项
const blackTypeOptionsCopy = ref<any>([]);
// 选择的行数据ids
const selectedIds = ref<any>(null);
// 选择的行数据
const selected = ref<any>(null);
let dialog = reactive<anyObj>({
	addOrUpdate: {
		// 打开状态
		open: false,
		// 标题
		title: '',
		// 表单数据
		form: {},
		// 按钮加载中状态
		btnLoading: false,
		// 表单校验规则
		rule: {
			type: [{ required: true, message: '类型必选', trigger: 'change' }],
			key: [{ required: true, message: 'key不能为空', trigger: 'blur' }],
			value: [{ required: true, message: 'value不能为空', trigger: 'blur' }],
		},
	},
});
const addOrUpdateForm = ref<any>();

onMounted(() => {
	options.blackTypeOptions.forEach((res) => {
		if (res.value) {
			blackTypeOptionsCopy.value.push(res);
		}
	});
	handlerQuery();
});

/**
 * 关闭新增或修改弹出层
 */
function closeAddOrUpdateDialog() {
	dialog.addOrUpdate.open = false;
}
/**
 * 选择行数据
 */
function handlerSelectionChange(selects: any) {
	selectedIds.value = selects.map((item: anyObj) => item.id);
	selected.value = selects;
}
/**
 * 搜索
 */
function handlerQuery() {
	tableConfig.loading = true;
	list(searchFormData).then((res: ApiResponse) => {
		tableConfig.loading = false;
		if (res.code !== 0) {
			return;
		}
		if (res.data !== null) {
			tableData.value = res.data.records;
			tableConfig.pagination.total = res.data.total;
		}
	});
}
/**
 * 表单提交
 */
function handlerSubmit() {
	if (dialog.addOrUpdate.title === '新增') {
		handlerAdd(undefined);
	} else {
		handlerEdit();
	}
}
/**
 * 新增
 */
function handlerAdd(filter: any) {
	let sign;
	if (typeof filter === 'function' && !(sign = filter())) {
		return;
	}
	// 判断窗口是否打开
	if (!dialog.addOrUpdate.open) {
		// 表单重置
		if (sign !== 'SET_FORM') {
			dialog.addOrUpdate.form = {};
			addOrUpdateForm.value?.resetFields();
		}
		// 标题
		dialog.addOrUpdate.title = '新增';
		// 打开窗口
		dialog.addOrUpdate.open = true;
		return;
	}
	// 校验参数
	addOrUpdateForm.value.validate((valid: any) => {
		if (!valid) {
			return;
		}
		// 调用接口
		dialog.addOrUpdate.btnLoading = true;
		add(dialog.addOrUpdate.form).then((res) => {
			dialog.addOrUpdate.btnLoading = false;
			if (res.code !== 0) {
				proxy.$modal.msgError(res.msg);
				return;
			}
			// 关闭弹出层
			closeAddOrUpdateDialog();
			// 刷新列表
			tableConfig.pagination.pageNum = 1;
			handlerQuery();
			// 提示
			proxy.$modal.msgSuccess('新增成功！');
		});
	});
}
/**
 * 修改
 */
function handlerEdit() {
	// 判断窗口是否打开
	if (!dialog.addOrUpdate.open) {
		// 数据回显，数据需要拷贝一下
		const d = JSON.parse(JSON.stringify(selected.value[0]));
		dialog.addOrUpdate.form = d;
		// 标题
		dialog.addOrUpdate.title = '修改';
		// 打开窗口
		dialog.addOrUpdate.open = true;
		return;
	}
	// 校验参数
	addOrUpdateForm.value.validate((valid: any) => {
		if (!valid) {
			return;
		}
		// 调用接口
		dialog.addOrUpdate.btnDisabled = true;
		edit(dialog.addOrUpdate.form).then((res) => {
			dialog.addOrUpdate.btnDisabled = false;
			if (res.code !== 0) {
				proxy.$modal.msgError(res.msg);
				return;
			}
			// 关闭弹出层
			closeAddOrUpdateDialog();
			// 刷新列表
			tableConfig.pagination.pageNum = 1;
			handlerQuery();
			// 提示
			proxy.$modal.msgSuccess('修改成功！');
		});
	});
}
/**
 * 删除
 */
function handlerDelete() {
	proxy.$modal
		.confirm('是否确认删除所选项?', '警告', {
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			type: 'warning',
		})
		.then(() => {
			// 调用接口
			return remove(selectedIds.value);
		})
		.then(() => {
			// 刷新列表 计算是否要查询上一页的数据
			if (tableConfig.pagination.total && tableConfig.pagination.pageSize) {
				// 删除后的总条数
				let totalCount = tableConfig.pagination.total - selectedIds.length;
				// 计算删除后的总页数
				let totalPage = Math.ceil(totalCount / tableConfig.pagination.pageSize);
				// 如果删除后的总页数小于1, 置为1
				totalPage = totalPage < 1 ? 1 : totalPage;
				// 判断删除前的页数是否大于删除后的总页数, 计算当前页应该是多少赋值给查询表单
				tableConfig.pagination.pageNum = tableConfig.pagination.pageNum > totalPage ? totalPage : tableConfig.pagination.pageNum;
			} else {
				tableConfig.pagination.pageNum = 1;
			}
			handlerQuery();
			// 提示
			proxy.$modal.msgSuccess('删除成功！');
		});
}
// 新增过滤器
function addFilter() {
	// 表单重置
	dialog.addOrUpdate.form = {};
	addOrUpdateForm.value?.resetFields();
	// 设置是否启用默认值
	dialog.addOrUpdate.form.isEnable = 0;
	return 'SET_FORM';
}
// 状态改变
function statusChange(row: anyObj, v: number) {
	row.isEnable = v;
	const d = JSON.parse(JSON.stringify(row));
	edit(d).then((res) => {
		if (res.code !== 0) {
			proxy.$modal.msgWarning(res.msg);
			return;
		}
		proxy.$modal.msgSuccess('设置成功');
	});
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.mt10 {
	margin-top: 10px;
}
</style>
